import { ref } from 'vue';
import { WebSocketHandler } from './WebSocketHandler';

const wsHandler = new WebSocketHandler();
const socket = ref(null);

const initSocket = (onMessageUpdate) => {
  if (typeof(onMessageUpdate) !== 'function') {
    return Promise.reject(new Error('Invalid onMessageUpdate parameter'));
  }

  // 如果已经有连接，直接返回现有的 Promise
  if (wsHandler.connectionPromise) {
    return wsHandler.connectionPromise;
  }

  wsHandler.setMessageCallback(onMessageUpdate);
  
  return new Promise((resolve, reject) => {
    wsHandler.connectionPromise = { resolve, reject };
    wsHandler.socket = new WebSocket('wss://cloud.nbmedicalsystem.com/ds/ws?accessToken=kfcs');
    socket.value = wsHandler.socket;

    wsHandler.socket.onopen = wsHandler.handleOpen;
    wsHandler.socket.onmessage = wsHandler.handleMessage;
    wsHandler.socket.onerror = wsHandler.handleError;
    wsHandler.socket.onclose = wsHandler.handleClose;
  });
};

const sendMessage = async (message) => {
  try {
    await wsHandler.connectionPromise;
    
    if (message?.body?.content) {
      wsHandler.medicalStore.sendQuestion(message.body.content);
    }

    if (wsHandler.socket?.readyState === WebSocket.OPEN) {
      wsHandler.socket.send(JSON.stringify(message));
      console.log('消息已发送:', message);
    } else {
      throw new Error('WebSocket 连接未打开');
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    throw error;
  }
};

export { initSocket, sendMessage };
